package com.bolingcavalry.crm.aftersales.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.base.ResponseResult;
import com.base.RoleEnum;
import com.bolingcavalry.crm.aftersales.mapper.AfterSalesMapper;
import com.bolingcavalry.crm.receiver.mapper.ReceiverMapper;
import com.bolingcavalry.crm.security.utils.SecurityUtils;
import com.bolingcavalry.crm.serviceorder.mapper.ServiceOrderMapper;
import com.bolingcavalry.crm.utils.AUtils;
import com.dto.aftersales.AfterSalesDTO;
import com.entity.aftersales.AfterSales;
import com.entity.serviceorder.ServiceOrder;
import com.vo.AfterSales.AfterSalesStatisVO;
import com.vo.AfterSales.AfterSalesVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Service
public class AfterSalesService {

    @Autowired
    private AfterSalesMapper afterSalesMapper;
    @Autowired
    private AUtils aUtils;
    @Autowired
    private ReceiverMapper receiverMapper;
    @Autowired
    private ServiceOrderMapper serviceOrderMapper;

    public AfterSalesVO getById(Long id) {
        AfterSales afterSales = afterSalesMapper.selectById(id);
        AfterSalesVO afterSalesVO = new AfterSalesVO();
        BeanUtils.copyProperties(afterSales, afterSalesVO);
        //传入售后单号去receiver表中查询对应的任务接收人的id
        List<Long> receiverIds=afterSalesMapper.getReceiverName(afterSalesVO.getOrderNumber());
        afterSalesVO.setReceiverName(new ArrayList<>());
        if(receiverIds!=null){
            for (Long receiverId : receiverIds) {
                afterSalesVO.getReceiverName().add(aUtils.getUserNickNameByUserId(receiverId));
            }
        }
        ServiceOrder serviceOrder = serviceOrderMapper.selectByOrderNumber(afterSalesVO.getOrderNumber());
        //查询服务地点去服务通知单中
        if(serviceOrder != null){
            afterSalesVO.setServiceLocation(serviceOrder.getServiceLocation());
            //获取联系人id，根据联系人id查询对应的姓名和手机号
            Long contactsId = serviceOrder.getCustomerContactsId();
            if(contactsId != null){
                afterSalesVO.setContactPerson(aUtils.getContactPersonById(contactsId));
                afterSalesVO.setPhoneNumber(aUtils.getPhoneNumberById(contactsId));
            }
        }
        afterSalesVO.setStartTime(afterSales.getStartTime());
        //如果客户id不为空的话，则根据id查询name
        if(null != afterSales.getCustomerId())
            afterSalesVO.setCustomerName(aUtils.getCustomerCompanyNameById(afterSales.getCustomerId()));
            afterSalesVO.setCustomerCompanyId(afterSales.getCustomerId());
        return afterSalesVO;
    }


    public ResponseResult save(AfterSalesDTO afterSalesdto) {
        AfterSales afterSales = new AfterSales();
        BeanUtils.copyProperties(afterSalesdto, afterSales);
        afterSales.setOrderNumber(generateOrderNumber());
        if(afterSalesdto.getCustomerId()==null){
            return ResponseResult.error("客户不能为空");
        }
        //设置创建时间为当前时间
        afterSales.setCreateTime(LocalDateTime.now());
        afterSales.setCreatedBy(aUtils.getNickNameByuserName(SecurityUtils.getCurrentUsername()));
        //判断是否存在同样的单号
        if(null == afterSalesMapper.selectByOrderNumber(afterSales.getOrderNumber())){
            if(afterSalesMapper.insert(afterSales) > 0)
                return ResponseResult.success("新增成功", afterSales.getOrderNumber());
        }
        return ResponseResult.error("新增失败");
    }

    /**
     * 生成服务单号，格式为：年份后两位+月份+四位序号
     * 例如：25080001（2025年8月第一单）
     * @return 生成的订单号
     */
    private String generateOrderNumber() {
        // 获取当前年月
        LocalDateTime now = LocalDateTime.now();
        String year = String.valueOf(now.getYear()).substring(2); // 取年份后两位
        String month = String.format("%02d", now.getMonthValue()); // 月份补零

        // 构造前缀
        String prefix = year + month;

        // 查询当前年月已有的最大序号
        String maxOrderNumber = afterSalesMapper.getMaxOrderNumberByPrefix(prefix);

        int nextSequence = 1;
        if (maxOrderNumber != null && !maxOrderNumber.isEmpty()) {
            // 从现有最大单号中提取序号并加1
            String sequenceStr = maxOrderNumber.substring(4); // 取后四位
            try {
                nextSequence = Integer.parseInt(sequenceStr) + 1;
            } catch (NumberFormatException e) {
                nextSequence = 1;
            }
        }

        // 格式化为4位序号
        String sequence = String.format("%04d", nextSequence);

        return prefix + sequence;
    }



    public boolean update(AfterSalesDTO afterSalesdto) {
        AfterSales afterSales = new AfterSales();
        BeanUtils.copyProperties(afterSalesdto, afterSales);
        //如果没有传入id，则根据单号查询id
        if(afterSales.getId()==null){
            Long idByServiceNumber = getIdByServiceNumber(afterSalesdto.getOrderNumber());
            afterSales.setId(idByServiceNumber);
        }
        if(afterSalesdto.getStartTime()!=null&&afterSalesdto.getEndTime()!=null){
            //如果都不为空，则计算出本次服务的天数存入服务天数字段中
            //afterSales.setServiceDays(aUtils.getServiceDays(afterSalesdto.getStartTime(), afterSalesdto.getEndTime()));
        }
        afterSales.setUpdateTime(LocalDateTime.now());
        afterSales.setOrderNumber(null);
        return afterSalesMapper.updateById(afterSales) > 0;
    }

    /**
     * 删除售后单
     * 权限：只有固定人员和创建人可以删除
     * @param id
     * @return
     */
    public ResponseResult deleteById(Long id) {
        //根据id查询售后单
        AfterSales afterSales = afterSalesMapper.selectById(id);
        if (afterSales == null) {
            return ResponseResult.error("售后单不存在");
        }
        // 权限检查：只有创建者或特定角色可以删除
        if(afterSales.getCreatedBy()==null){
            return ResponseResult.error("售后创建人为空删除出错，请建立挂管理员处理");
        }
        String currentUsername = aUtils.getNickNameByuserName(SecurityUtils.getCurrentUsername());
        List<String> currentUserRoles = SecurityUtils.getCurrentUserRoles();
        boolean isCreator = afterSales.getCreatedBy().equals(currentUsername);
        boolean hasSpecialRole = false;
        if (currentUserRoles != null) {
            for (String role : currentUserRoles) {
                if (RoleEnum.ADMIN.getCode().equals(role) ||
                        RoleEnum.TECHNICAL_COMMAND.getCode().equals(role) ||
                        RoleEnum.GENERAL_COMMAND.getCode().equals(role) ||
                        RoleEnum.DEPARTMENT_LEADER.getCode().equals(role) ||
                        RoleEnum.LEADER.getCode().equals(role)) {
                    hasSpecialRole = true;
                    break;
                }
            }
        }
        if (!isCreator && !hasSpecialRole) {
            return ResponseResult.error("您没有权限删除该售后单");
        }
        //根据id查询name
        String serviceNumber = afterSales.getOrderNumber();
        //判断是否有子表数据有则不允许删除（检查四个订单下是否包含数据）
        if(hasChildren(serviceNumber)){
            return ResponseResult.error("该售后问题下有订单数据，不允许删除！");
        }
        afterSalesMapper.deleteById(id);
        return ResponseResult.success("删除成功");
    }


    /**
     * 判断是否有子表数据有则不允许删除（检查四个订单下是否包含数据）
     * @param serviceNumber
     * @return
     */
    public boolean hasChildren(String serviceNumber) {
        int countSales = afterSalesMapper.checkserviceOrders(serviceNumber);
        int countTask = afterSalesMapper.checkTaskOrders(serviceNumber);
        int countConfirm = afterSalesMapper.checkConfirmationOrders(serviceNumber);
        int countSummary = afterSalesMapper.checkSummaryOrders(serviceNumber);
        return countSales > 0 || countTask > 0 || countConfirm > 0 || countSummary > 0;
    }

    /**
     * 转换为VO
     * @param afterSales
     * @return
     */
    private AfterSalesVO convertToVO(AfterSales afterSales) {
        AfterSalesVO vo = new AfterSalesVO();
        BeanUtils.copyProperties(afterSales, vo);

        // 客户名称
        if (afterSales.getCustomerId() != null) {
            vo.setCustomerName(aUtils.getCustomerCompanyNameById(afterSales.getCustomerId()));
            vo.setCustomerCompanyId(afterSales.getCustomerId());
        }

        // 接收人名称（批量处理）
        List<Long> receiverIds = afterSalesMapper.getReceiverName(vo.getOrderNumber());
        if (!CollectionUtils.isEmpty(receiverIds)) {
            List<String> receiverNames = aUtils.getUserNickNamesByIds(receiverIds); // 批量查询
            vo.setReceiverName(receiverNames);
        } else {
            vo.setReceiverName(Collections.emptyList());
        }
        // 添加服务地点和联系人信息
        ServiceOrder serviceOrder = serviceOrderMapper.selectByOrderNumber(vo.getOrderNumber());
        if (serviceOrder != null) {
            vo.setServiceLocation(serviceOrder.getServiceLocation());
            // 获取联系人id，根据联系人id查询对应的姓名和手机号
            Long contactsId = serviceOrder.getCustomerContactsId();
            if (contactsId != null) {
                vo.setContactPerson(aUtils.getContactPersonById(contactsId));
                vo.setPhoneNumber(aUtils.getPhoneNumberById(contactsId));
            }
        }

        return vo;
    }

    /**
     * 条件查询售后单
     * @param pageNum
     * @param pageSize
     * @param serviceNumber
     * @param customerName
     * @param receiverName
     * @param startTime
     * @param endTime
     * @param status
     * @param keyword
     * @param projectType
     * @return
     */
    public IPage<AfterSalesVO> getByConditions(Integer pageNum, Integer pageSize, String serviceNumber, String customerName,
                                               String receiverName, String startTime, String endTime, String status,
                                               String keyword, String projectType) {

        // 构建查询条件
        LambdaQueryWrapper<AfterSales> wrapper = new LambdaQueryWrapper<>();

        // 获取当前登录用户信息
        String nickname = aUtils.getNickNameByuserName(SecurityUtils.getCurrentUsername());
        List<String> roles = SecurityUtils.getCurrentUserRoles();

        // 添加权限过滤条件
        addPermissionFilter(wrapper, nickname, roles);

        // keyword 模糊匹配
        if (StringUtils.hasText(keyword)) {
            handleKeywordSearch(wrapper, keyword);
        }


        // 客户名称查询
        if (StringUtils.hasText(customerName)) {
            List<Long> companyIds = afterSalesMapper.selectCustomerCompanyIdsByName(customerName);
            if (CollectionUtils.isEmpty(companyIds)) {
                wrapper.eq(AfterSales::getId, -1L);
            } else {
                wrapper.in(AfterSales::getCustomerId, companyIds);
            }
        }

        // 服务单号查询
        if (StringUtils.hasText(serviceNumber)) {
            handleServiceNumberSearch(wrapper, serviceNumber);
        }

        // 接收人名称查询
        if (StringUtils.hasText(receiverName)) {
            handleReceiverNameSearch(wrapper, receiverName);
        }

        // 时间范围
        if (StringUtils.hasText(startTime)) {
            wrapper.ge(AfterSales::getStartTime, startTime);
        }
        if (StringUtils.hasText(endTime)) {
            wrapper.le(AfterSales::getStartTime, endTime);
        }

        // 状态
        if (StringUtils.hasText(status)) {
            if (status.contains(",")) {
                wrapper.in(AfterSales::getStatus, Arrays.asList(status.split(",")));
            } else {
                wrapper.eq(AfterSales::getStatus, status);
            }
        }

        // 项目类型
        if (StringUtils.hasText(projectType)) {
            wrapper.eq(AfterSales::getProjectType, projectType);
        }

        wrapper.orderByDesc(AfterSales::getOrderNumber);

        // 分页
        Page<AfterSales> page = new Page<>(pageNum, pageSize != null ? pageSize : 100);
        IPage<AfterSales> resultPage = afterSalesMapper.selectPage(page, wrapper);

        // VO 转换（批量处理）
        IPage<AfterSalesVO> voPage = resultPage.convert(this::convertToVO);

        return voPage;
    }



    private void handleKeywordSearch(LambdaQueryWrapper<AfterSales> wrapper, String keyword) {
        // 1. 客户名称模糊匹配
        List<Long> companyIds = afterSalesMapper.selectCustomerCompanyIdsByName(keyword);
        boolean hasCompany = !CollectionUtils.isEmpty(companyIds);

        // 2. 服务单号模糊匹配
        List<Long> salesOrderIds = afterSalesMapper.selectIdsByOrderNumber(keyword);
        boolean hasOrder = !CollectionUtils.isEmpty(salesOrderIds);

        // 3. 任务接收人模糊匹配
        List<Long> userIdsByName = aUtils.getUserIdsByNamemohu(keyword);
        List<String> orderNumbers = new ArrayList<>();
        if (!CollectionUtils.isEmpty(userIdsByName)) {
            // 批量查询订单号，避免循环查询
            for (Long userId : userIdsByName) {
                orderNumbers.addAll(receiverMapper.selectOrderNumberByuserId(userId));
            }
        }
        boolean hasReceiver = !orderNumbers.isEmpty();

        // 4. 构建 OR 查询条件
        if (hasCompany || hasOrder || hasReceiver) {
            wrapper.and(i -> {
                boolean first = true;
                if (hasCompany) {
                    i.in(AfterSales::getCustomerId, companyIds);
                    first = false;
                }
                if (hasOrder) {
                    if (!first) i.or();
                    i.in(AfterSales::getId, salesOrderIds);
                    first = false;
                }
                if (hasReceiver) {
                    if (!first) i.or();
                    i.in(AfterSales::getOrderNumber, orderNumbers);
                }
            });
        } else {
            // 如果没有任何匹配，构造一个永远不成立的条件
            wrapper.eq(AfterSales::getId, -1L);
        }
    }


    private void handleServiceNumberSearch(LambdaQueryWrapper<AfterSales> wrapper, String serviceNumber) {
        if (serviceNumber.matches("\\d{4}-")) {
            // 处理 2025- 格式
            String yearPrefix = serviceNumber.substring(2, 4);
            List<Long> orderIds = afterSalesMapper.selectIdsByOrderNumberYearPrefix(yearPrefix);
            if (!CollectionUtils.isEmpty(orderIds)) {
                wrapper.in(AfterSales::getId, orderIds);
            } else {
                wrapper.eq(AfterSales::getId, -1L);
            }
        } else if (serviceNumber.matches("\\d{4}-\\d{2}")) {
            // 处理 2025-08 格式
            String yearPrefix = serviceNumber.substring(2, 4);
            String month = serviceNumber.substring(5, 7);
            String yearMonthPrefix = yearPrefix + month;
            List<Long> orderIds = afterSalesMapper.selectIdsByOrderNumberYearMonthPrefix(yearMonthPrefix);
            if (!CollectionUtils.isEmpty(orderIds)) {
                wrapper.in(AfterSales::getId, orderIds);
            } else {
                wrapper.eq(AfterSales::getId, -1L);
            }
        } else {
            // 精确匹配
            List<Long> orderIds = afterSalesMapper.selectIdsByOrderNumber(serviceNumber);
            if (!CollectionUtils.isEmpty(orderIds)) {
                wrapper.in(AfterSales::getId, orderIds);
            } else {
                wrapper.eq(AfterSales::getId, -1L);
            }
        }
    }

    private void handleReceiverNameSearch(LambdaQueryWrapper<AfterSales> wrapper, String receiverName) {
        List<Long> userIdsByName = aUtils.getUserIdsByNamemohu(receiverName);
        if (!CollectionUtils.isEmpty(userIdsByName)) {
            List<String> orderNumbers = new ArrayList<>();
            for (Long userId : userIdsByName) {
                orderNumbers.addAll(receiverMapper.selectOrderNumberByuserId(userId));
            }
            if (!orderNumbers.isEmpty()) {
                wrapper.in(AfterSales::getOrderNumber, orderNumbers);
            } else {
                wrapper.eq(AfterSales::getId, -1L);
            }
        } else {
            wrapper.eq(AfterSales::getId, -1L);
        }
    }



    /**
     * 添加权限过滤条件
     * @param wrapper 查询条件构造器
     * @param nickname 当前用户名
     * @param roles 当前用户角色列表
     */
    private void addPermissionFilter(LambdaQueryWrapper<AfterSales> wrapper, String nickname, List<String> roles) {
        // 检查是否是管理员、部门负责人或领导或技术指挥部和综合指挥部
        boolean isAdminOrLeader = false;
        if (roles != null) {
            for (String role : roles) {
                if (RoleEnum.ADMIN.getCode().equals(role) ||
                        RoleEnum.DEPARTMENT_LEADER.getCode().equals(role) ||
                        RoleEnum.LEADER.getCode().equals(role)||
                        RoleEnum.TECHNICAL_COMMAND.getCode().equals(role) ||
                        RoleEnum.GENERAL_COMMAND.getCode().equals(role)) {
                    isAdminOrLeader = true;
                    break;
                }
            }
        }

        // 如果不是管理员等角色，则添加权限过滤条件
        if (!isAdminOrLeader) {
            // 获取当前用户ID
            Long currentUserId = aUtils.getUserIdByNickName(nickname);

            wrapper.and(permissionWrapper -> {
                // 条件1：创建人是当前用户
                permissionWrapper.eq(AfterSales::getCreatedBy, nickname);

                // 条件2：当前用户是任务接收人
                if (currentUserId != null) {
                    permissionWrapper.or()
                            .apply("EXISTS (SELECT 1 FROM receiver WHERE receiver.order_number = after_sales.order_number AND receiver.user_id = {0})", currentUserId);
                }
            });
        }
    }


    /**
     * 查询售后问题统计信息
     * @return
     */
    public Object getcount() {
        AfterSalesStatisVO vo = new AfterSalesStatisVO();
        vo.setMonthlyCount(afterSalesMapper.countMonthly());  // 查询本月售后问题数
        vo.setAnnualCount(afterSalesMapper.countAnnual());     // 查询全年售后问题数
        vo.setInProgressCount(afterSalesMapper.countInProgress()); // 查询当前进行中的售后问题数
        vo.setCompletedThisMonthCount(afterSalesMapper.countCompletedThisMonth()); // 查询本月已完结的售后问题数
        return vo;
    }

    public Long getIdByServiceNumber(String orderNumber) {
        LambdaQueryWrapper<AfterSales> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AfterSales::getOrderNumber, orderNumber);
        return afterSalesMapper.selectOne(wrapper).getId();
    }

    public List<AfterSalesVO> getByServiceNumber(String serviceNumber) {
        LambdaQueryWrapper<AfterSales> wrapper = new LambdaQueryWrapper<>();
        // 如果传入了serviceNumber且不为空，则进行模糊查询
        if (StringUtils.hasText(serviceNumber)) {
            wrapper.like(AfterSales::getOrderNumber, serviceNumber);
        }
        // 如果serviceNumber为空，则查询全部数据
        List<AfterSales> afterSales = afterSalesMapper.selectList(wrapper);
        List<AfterSalesVO> afterSalesVOS = new ArrayList<>();
        for (AfterSales afterSale : afterSales) {
            AfterSalesVO afterSalesVO = convertToVO(afterSale);
            afterSalesVOS.add(afterSalesVO);
        }
        return afterSalesVOS;
    }

}